<template>
  <div class="shopping-cart">
    <h2>🛒 智能购物车</h2>
    
    <div class="product-list">
      <h3>🥤 商品列表</h3>
      <div class="products">
        <div v-for="product in products" :key="product.id" class="product-item">
          <div class="product-info">
            <span class="product-name">{{ product.name }}</span>
            <span class="product-price">¥{{ product.price }}</span>
          </div>
          <div class="product-controls">
            <button @click="decreaseQuantity(product)" :disabled="product.quantity <= 0">-</button>
            <span class="quantity">{{ product.quantity }}</span>
            <button @click="increaseQuantity(product)">+</button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="cart-summary">
      <h3>📋 订单摘要</h3>
      <div class="summary-item">
        <span>商品总数：</span>
        <span>{{ totalQuantity }} 件</span>
      </div>
      <div class="summary-item">
        <span>商品总价：</span>
        <span>¥{{ subtotal.toFixed(2) }}</span>
      </div>
      <div class="summary-item">
        <span>折扣率：</span>
        <span>{{ (discount * 100).toFixed(0) }}%</span>
      </div>
      <div class="summary-item">
        <span>优惠金额：</span>
        <span>-¥{{ discountAmount.toFixed(2) }}</span>
      </div>
      <div class="summary-item total">
        <span>应付金额：</span>
        <span class="total-price">¥{{ total.toFixed(2) }}</span>
      </div>
    </div>
    
    <div class="discount-info">
      <h4>💰 优惠活动</h4>
      <div class="discount-rules">
        <div 
          v-for="rule in discountRules" 
          :key="rule.threshold"
          :class="['discount-rule', { 'active': subtotal >= rule.threshold }]"
        >
          <span>满 ¥{{ rule.threshold }} 享 {{ (rule.discount * 100).toFixed(0) }}% 折扣</span>
          <span class="rule-status">{{ subtotal >= rule.threshold ? '✅' : '⏳' }}</span>
        </div>
      </div>
    </div>
    
    <div class="actions">
      <button @click="clearCart" class="clear-btn">
        🗑️ 清空购物车
      </button>
      <button @click="checkout" class="checkout-btn" :disabled="totalQuantity <= 0">
        💳 立即结算
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

// 商品接口定义
interface Product {
  id: number
  name: string
  price: number
  quantity: number
}

// 折扣规则接口定义
interface DiscountRule {
  threshold: number
  discount: number
}

// 商品数据
const products = ref<Product[]>([
  { id: 1, name: '珍珠奶茶', price: 15, quantity: 0 },
  { id: 2, name: '芝士奶盖', price: 18, quantity: 0 },
  { id: 3, name: '抹茶拿铁', price: 22, quantity: 0 },
  { id: 4, name: '焦糖玛奇朵', price: 25, quantity: 0 },
  { id: 5, name: '草莓果茶', price: 16, quantity: 0 },
  { id: 6, name: '柠檬蜂蜜', price: 12, quantity: 0 }
])

// 折扣规则
const discountRules = ref<DiscountRule[]>([
  { threshold: 50, discount: 0.95 },   // 满50享95折
  { threshold: 100, discount: 0.9 },  // 满100享9折
  { threshold: 200, discount: 0.85 } // 满200享85折
])

// 计算商品总数
const totalQuantity = computed<number>(() => {
  return products.value.reduce((sum, product) => sum + product.quantity, 0)
})

// 计算商品小计（原价总和）
const subtotal = computed<number>(() => {
  return products.value.reduce((sum, product) => sum + (product.price * product.quantity), 0)
})

// 计算适用的折扣率
const discount = computed<number>(() => {
  const applicableRule = discountRules.value
    .filter(rule => subtotal.value >= rule.threshold)
    .sort((a, b) => b.discount - a.discount)[0] // 取最大折扣
  
  return applicableRule ? applicableRule.discount : 1 // 默认无折扣
})

// 计算优惠金额
const discountAmount = computed<number>(() => {
  return subtotal.value * (1 - discount.value)
})

// 计算应付总金额（带缓存的计算属性）
const total = computed<number>(() => {
  console.log('🧮 正在计算订单总价...')
  return subtotal.value * discount.value
})

// 增加商品数量
const increaseQuantity = (product: Product) => {
  product.quantity++
}

// 减少商品数量
const decreaseQuantity = (product: Product) => {
  if (product.quantity > 0) {
    product.quantity--
  }
}

// 清空购物车
const clearCart = () => {
  products.value.forEach(product => {
    product.quantity = 0
  })
  console.log('🗑️ 购物车已清空')
}

// 结算
const checkout = () => {
  if (totalQuantity.value > 0) {
    console.log(`💳 订单结算：${total.value.toFixed(2)}元，共${totalQuantity.value}件商品`)
    alert(`🎉 订单提交成功！\n💰 应付金额：¥${total.value.toFixed(2)}\n📦 商品数量：${totalQuantity.value}件`)
  }
}
</script>

<style scoped>
.shopping-cart {
  max-width: 800px;
  margin: 30px auto;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  color: white;
  font-family: 'Arial', sans-serif;
}

.shopping-cart h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 28px;
}

.shopping-cart h3 {
  margin-bottom: 20px;
  font-size: 20px;
}

.shopping-cart h4 {
  margin-bottom: 15px;
  font-size: 16px;
}

.product-list, .cart-summary, .discount-info {
  background: rgba(255, 255, 255, 0.1);
  padding: 25px;
  border-radius: 15px;
  margin-bottom: 25px;
}

.products {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.05);
  padding: 15px;
  border-radius: 10px;
  transition: background 0.3s ease;
}

.product-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
}

.product-price {
  font-size: 18px;
  color: #42b883;
  font-weight: bold;
}

.product-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-controls button {
  width: 30px;
  height: 30px;
  border: none;
  border-radius: 50%;
  background: #42b883;
  color: white;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.product-controls button:hover:not(:disabled) {
  background: #369870;
  transform: scale(1.1);
}

.product-controls button:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
}

.quantity {
  font-size: 18px;
  font-weight: bold;
  min-width: 30px;
  text-align: center;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-item.total {
  font-size: 20px;
  font-weight: bold;
  color: #42b883;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 2px solid rgba(255, 255, 255, 0.2);
}

.total-price {
  font-size: 24px;
  color: #ff6b6b;
}

.discount-rules {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.discount-rule {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.discount-rule.active {
  background: rgba(66, 184, 131, 0.2);
  border: 1px solid rgba(66, 184, 131, 0.5);
}

.rule-status {
  font-size: 16px;
}

.actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.clear-btn, .checkout-btn {
  padding: 15px 30px;
  font-size: 16px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: bold;
}

.clear-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.checkout-btn {
  background: #42b883;
  color: white;
}

.checkout-btn:hover:not(:disabled) {
  background: #369870;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.checkout-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
}
</style>